package com.cs171.market.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.UUID;

/**
 * @author yangyifei
 * @version 1.0
 * @date 2020/6/21 10:12
 */
@CrossOrigin
@RestController
public class FileController {
//    @GetMapping("tmp_uploads/{file_path}")
//    public String file(){
//        return "file";
//    }

    @PostMapping("upload")
    public Object postPic(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
        JSONObject result = jsonhead();
        if (file.isEmpty()) {
            System.out.println("文件为空");
            return result;
        }
        else{
            String fileName = file.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String filePath = "C://tmp//"; // 上传后的路径
            fileName = UUID.randomUUID() + suffixName; // 新文件名
            File dest = new File(filePath + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            String hostIP = "http://localhost:8080/cs/";
            JSONObject dataJson = new JSONObject();
            try {
                file.transferTo(dest);
                String filename = "/tmp_uploads/" + fileName;
                dataJson.put("tmp_path", filename);
                dataJson.put("url", hostIP+filename);
            } catch (IOException e) {
                e.printStackTrace();
            }
        result.put("data", dataJson);
        }
        return result;
    }

    /**
     * 重构代码，相似的Json Head
     * @return JsonObject
     */
    private JSONObject jsonhead(){
        JSONObject pAll = new JSONObject();
        JSONObject pSuccess = new JSONObject();
        pSuccess.put("msg", "上传成功");
        pSuccess.put("status", "200");
        pAll.put("meta", pSuccess);
        return pAll;
    }
}
